package cn.com.pg.b2b.pd.truck.appointment.management.service.service.impl;

import cn.com.pg.b2b.pd.truck.appointment.management.service.mapper.LineStepMapper;
import cn.com.pg.b2b.pd.truck.appointment.management.service.model.dto.LineStepDTO;
import cn.com.pg.b2b.pd.truck.appointment.management.service.model.entity.LineStep;
import cn.com.pg.b2b.pd.truck.appointment.management.service.service.LineStepService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 线路节点 服务实现类
 * </p>
 *
 * @author 王开琦
 * @since 2023-06-08
 */
@Service
public class LineStepServiceImpl implements LineStepService {
    private final LineStepMapper lineStepMapper;

    public LineStepServiceImpl(LineStepMapper lineStepMapper) {
        this.lineStepMapper = lineStepMapper;
    }

    @Override
    public void add(LineStepDTO lineStepDTO) {
        //1. 将 dto 转换为保存的 entity
        LineStep saveEntity = LineStep.from(lineStepDTO);
        //2. 保存
        lineStepMapper.insert(saveEntity);
    }

    @Override
    public void deleteByLineStepIds(List<Integer> lineStepIds) {
        lineStepMapper.deleteBatchIds(lineStepIds);
    }

    @Override
    public void update(LineStepDTO lineStepDTO) {
        //1. 根据 id 查询
        LineStep lineStep = lineStepMapper.selectById(lineStepDTO.getLineStepId());
        //2. 将 dto 转换成 entity
        LineStep updateEntity = LineStep.from(lineStep, lineStepDTO);
        //3. 保存
        lineStepMapper.updateById(updateEntity);
    }

    @Override
    public List<LineStepDTO> getByLineStepIds(List<Integer> lineStepIds) {
        if (lineStepIds.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        List<LineStep> lineSteps = lineStepMapper.selectBatchIds(lineStepIds);
        return lineSteps.stream().filter(LineStep::getIsValidFlag).map(LineStep::to).collect(Collectors.toList());
    }

    @Override
    public List<LineStepDTO> getByLineId(Integer lineId) {
        LambdaQueryWrapper<LineStep> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LineStep::getLineId, lineId).eq(LineStep::getIsValidFlag, true);
        List<LineStep> lineStepList = lineStepMapper.selectList(lambdaQueryWrapper);
        return lineStepList.stream().map(LineStep::to).collect(Collectors.toList());
    }
}
